package com.k.kpp.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.*;

public class Dom4jUtil {
    public static void main(String[] args) {
        try {
            parseXml();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取SOAP内容 到 Map<resKey,List<Map>>
     * @throws DocumentException
     */
    private static void parseXml() throws DocumentException {
        Map<String,List> resultZ = new HashMap<>();
        List<Map<String,Object>> result = new ArrayList<>();
        File file = new File("C:/test/a.xml");
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);
        Element root = document.getRootElement();
        try {
            String rootName = root.getName();
            Element bodyEle = root.element("Body");
            List<Element> responseList = bodyEle.elements();
            for(Element ele:responseList){
                //getOneResponse
                String responseName = ele.getName();
                List<Element> wrapList = ele.elements();
                for(Element wrapEle:wrapList){
                    // wrap
                    boolean hasM = wrapEle.hasMixedContent();
                    if(hasM){
                        List<Element> itmList = wrapEle.elements();
                        Map<String,Object> map = new HashMap<>();
                        for(Element itm:itmList ){
                            // itm
                            System.out.println(itm.getName()+":");
                            map.put(itm.getName(),itm.getStringValue());
                        }
                        result.add(map);
                    }else{
                        System.out.println("else...");
                        Map<String,Object> map = new HashMap<>();
                        map.put(wrapEle.getName(),wrapEle.getStringValue());
                        result.add(map);
                    }
                }
                resultZ.put(responseName,result);
            }
            System.out.println(resultZ);
            //getMap(bodyEle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void mapToInsertSQL(Map<String,List<Map<String,Object>>> map){
        for(Map.Entry<String,List<Map<String,Object>>> entry:map.entrySet()){
            String key = entry.getKey();
            List<Map<String,Object>> value = entry.getValue();
            if(value.size()>0){
                Map<String,Object> itmMap = value.get(0);
                // insert into tb() values();
            }
        }
    }

}
